package com.mack.alioss.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

import com.mack.alioss.config.AliOssconfig;
import com.mack.alioss.entity.OssToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;


@Service
public class OssService {

    @Autowired
    private AliOssconfig aliOssconfig;


    public OssToken getToken(){
        DefaultProfile profile = DefaultProfile.getProfile(aliOssconfig.getRegionID(), aliOssconfig.getAccessKeyId(),aliOssconfig.getAccessKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleSessionName("mack");
        request.setRoleArn(aliOssconfig.getRoleArn());
        request.setDurationSeconds (1080L);
        try {
            AssumeRoleResponse acsResponse = client.getAcsResponse(request);
            //拿到前端需要的数据了
            AssumeRoleResponse.Credentials credentials = acsResponse.getCredentials();
            String accessKeyId = credentials.getAccessKeyId();
            String accessReySecret = credentials.getAccessKeySecret();
            String securityToken = credentials.getSecurityToken();
            //构建前端需要的vo
            return OssToken.builder()
                    .accesskeyId(accessKeyId)
                    .accesskeySecret(accessReySecret).stsToken(securityToken)
                    .region("oss-"+aliOssconfig.getRegionID()).bucket(aliOssconfig.getBucket())
                    .build();
        }catch (ClientException exception){
            System.out.println(exception);
        }
        return null;
    }
}
